package data
{
	import com.maclema.mysql.MySqlToken;
	import com.maclema.mysql.ResultSet;
	
	import controls.DataRequestor;
	import controls.events.ServiceEvent;
	
	import flash.events.EventDispatcher;
	
	public class Professor extends EventDispatcher
	{
		public var firstName:String;
		public var lastName:String;
		public var id:int;
		public var gpa:Number;
		public var grades:Array;
		
		public function Professor(prof:String = null)
		{
			id = -1;
			gpa = 0;
			firstName = lastName = "";
			grades = [];
			
			if(prof != null)
			{
				if(prof.indexOf("TBA") != -1)
				{
					lastName = "TBA";
					this.dispatchEvent(new ServiceEvent(ServiceEvent.PROFESSOR_LOADED, this));
				}
				else
				{
					var names:Array = prof.split(", ");
					firstName = names[1];
					lastName = names[0];
					getGPAInfo();
				}
			}
		}

		public function getCourseGPAInfo(title:String):void
		{
			if(lastName == "TBA")	return;
			var requestor:DataRequestor = DataRequestor.instance;
			requestor.getProfessorCourseGPA(this, title, parseCourseGPA);
		}

		public function getGPAInfo():void
		{
			var requestor:DataRequestor = DataRequestor.instance;
			requestor.getProfessorGPA(this, parseGPA);
		}
		
		private function parseCourseGPA(sqlData:Object, token:MySqlToken):void
		{
			var rs:ResultSet = sqlData as ResultSet;
			for each(var row:Object in rs.getRows())
				grades.push(new GradeInfo(row));
			
			this.dispatchEvent(new ServiceEvent(ServiceEvent.COURSES_LOADED, this));
		}
		
		private function parseGPA(sqlData:Object, token:MySqlToken):void
		{
			if(sqlData is ResultSet)
			{
				var rs:ResultSet = sqlData as ResultSet;
				for each(var row:Object in rs.getRows())
				{
					id = row.ProfID;
					gpa = row.ProfGPA;
				}
			}
			else
				trace("Proffesor Error: " + sqlData);
			
			this.dispatchEvent(new ServiceEvent(ServiceEvent.PROFESSOR_LOADED, this));
		}
		
		public function get name():String
		{
			return lastName + ", " + firstName;
		}
	}
}